package com.song.oa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.song.oa.entity.R;
import com.song.oa.pojo.Admin;
import com.song.oa.mapper.AdminMapper;
import com.song.oa.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.song.oa.util.JwtTokenUtil;
import com.song.oa.vo.Login;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.lang.reflect.MalformedParameterizedTypeException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tonysong
 * @since 2024-03-19
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private PasswordEncoder passwordEncoder;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
//    private AdminService adminService;
    private LoginUserService loginUserService;
//    @Override
//    public Admin findAdminByUsername(String username) {
//        return  this.loginUserService.loadUserByUsername(username);
//        //return this.adminService.getOne(new QueryWrapper<Admin>().eq("username", username).eq("enabled", 1));
//    }
    @Override
    public R login(String username, String password, String code, HttpServletRequest request) {
        UserDetails userDetails = this.loginUserService.loadUserByUsername(username);
        if(Objects.isNull(userDetails) || !passwordEncoder.matches(password, userDetails.getPassword())){
            return  new R(302, false, "用户名或密码错误！");
        }
        if(!userDetails.isEnabled()){
            return  new R(303, false, "账号被禁用，请联系管理员！");
        }
        //更新Security登录对象信息
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //后端生成token
        String token = this.jwtTokenUtil.generateToken(userDetails);
        Map<String,Object> map = new HashMap<>(5);
        map.put("token", token);
        map.put("tokenHead",tokenHead);
        return new R(200,true ,"登录成功！", map);

    }
}
